from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.permissions import IsAdminUser

from meiduo_admin.serializers.orders import OrderSerializer
from meiduo_admin.utils import PageNum
from orders.models import OrderInfo


class OrderView(ReadOnlyModelViewSet):
    permission_classes = [IsAdminUser]
    queryset = OrderInfo.objects.all()
    serializer_class = OrderSerializer
    pagination_class = PageNum

    def get_queryset(self):
        if self.request.query_params.get("keyword") == "" or self.request.query_params.get("keyword") is None:
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id=self.request.query_params.get("keyword"))
    @action(methods=["put"],detail=True)
    def status(self, request, pk):
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except Exception as e:
            return Response({'error': '订单编号不对'})

        status = request.data.get('status')
        order.status = status
        order.save()
        return Response({
            'order_id': order.order_id,
            'status': status
        })
